#include "CTextTable.h"
#include <QDebug>
#include "SqlTool.h"
#include <QSqlQuery>
#include <QSqlRecord>

CTextTable::CTextTable(QString strTableName,QStringList strListColumnNames,QObject *parent)
    : AbsTable(strTableName,parent),m_strListColumnNames(strListColumnNames)
{
    if(m_strListColumnNames.isEmpty()){
        qCritical()<<"Db Tablename: "<<m_strTableName<<" ,header is empty! Can't create table!";
        return ;
    }

    if(!exisit()){
       createTable();
    }
}

bool CTextTable::createTable()
{
    QString SQL = SqlTool::SQL_CREATE_TABLE(m_strTableName,m_strListColumnNames);
    bool bSuccess = execSql(SQL);
    if(!bSuccess){
        qCritical()<<"表创建失败! SQL:"<<SQL;
    }

    return bSuccess;
}

bool CTextTable::addRow(QVariantList varList)
{
    QString SQL = SqlTool::SQL_INSERT_ROW(m_strTableName,varList);
    return AbsTable::execSql(SQL);
}

bool CTextTable::deleteRow(QString strId)
{
    QString SQL = SqlTool::SQL_DELETE(m_strTableName,m_strListColumnNames.first(),strId);
    return AbsTable::execSql(SQL);
}

bool CTextTable::updateRow(QVariantList varList)
{
    QString SQL = SqlTool::SQL_UPDATE_ROW(m_strTableName,m_strListColumnNames,varList);
    return AbsTable::execSql(SQL);
}

bool CTextTable::updateColumn(QString strId, int nColumnIndex, QString strColumnVal)
{
    QString SQL = SqlTool::SQL_UPDATE_COLUMN(m_strTableName,m_strListColumnNames.first(),strId,
                                             m_strListColumnNames[nColumnIndex],strColumnVal);
    return AbsTable::execSql(SQL);
}

QVariantList CTextTable::queryRow(QString strId)
{
    QString SQL = SqlTool::SQL_QUERY(m_strTableName,m_strListColumnNames.first(),strId);
    QSqlQuery query(*dbConnection());
    QVariantList varList;
    if(query.exec(SQL)){
        QSqlRecord sqlRcd = query.record(); //通过此获取结果列数
        while (query.next()) {
            for(int i = 0; i < sqlRcd.count(); i++){
                varList.append(query.value(i));
            }
        }
    }else{
        qWarning()<<"query row err!";
    }

    return varList;
}

QVector<QVariantList> CTextTable::queryAll()
{
    QString SQL = SqlTool::SQL_QUERY_ALL(m_strTableName);
    QSqlQuery query(*dbConnection());
    QVector<QVariantList> varListRows;

    if(query.exec(SQL)){
        QSqlRecord sqlRcd = query.record(); //通过此获取结果列数
        while (query.next()) {
            QVariantList varList;
            for(int i = 0; i < sqlRcd.count(); i++){
                varList.append(query.value(i));
            }
            varListRows.append(varList);
        }
    }else{
        qWarning()<<"queryAll err!";
    }

    return varListRows;
}
